package shared.file


trait TimeUnit {
  def next: TimeUnit
  def nextScale: Int 
  def unit:String
}

case class Time(val t: Int, val unit: TimeUnit)  {
  override def toString = t + " " + unit.unit 
}

class CompoundTime(val ts: List[Time]) {
  
  override def toString = ts.mkString("", " ", "")
  
  def mostSignificant(n: Int) = {
    if(ts.size > n) {
      new CompoundTime(ts.take(n))
    } else {
      this
    }
  }
  
  def mostSignificant:CompoundTime = mostSignificant(1)
  
}

object TimeUnitFormatter {

  object Months extends TimeUnit {
    def next = Months
    def nextScale = Integer.MAX_VALUE
    def unit = "months"
  }
  
  object Days extends TimeUnit {
    def next = Months
    def nextScale = 30
    def unit = "days"
  }
  
  object Hours extends TimeUnit {
    def next = Days
    def nextScale = 24
    def unit = "hours"
  }
  
  object Minutes extends TimeUnit {
    def next = Hours
    def nextScale = 60
    def unit = "minutes"
  }
  
  object Seconds extends TimeUnit {
    def next = Minutes
    def nextScale = 60
    def unit = "seconds"
  }
  
  object Millis extends TimeUnit {
    def next = Seconds
    def nextScale = 1000
    def unit = "milliseconds"
  }
  
  
  def format(v: Int, tu: TimeUnit):CompoundTime = {
    def formatR(n: Int, t: TimeUnit, l: List[Time]):List[Time] = {
      if(n > tu.nextScale) {
        formatR(n / tu.nextScale, tu.next, new Time(n % tu.nextScale, t) :: l)
      } else {
        new Time(n, t) :: l
      }
    }
    new CompoundTime(formatR(v, tu, Nil))
  }
  
  def formatMillis(v: Int):CompoundTime = { format(v, Millis)}
  
  
}
